<?php

namespace ShowStop\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

use ShowStop\TelevisionBundle\Entity\Series;

/**
* @Route("/admin")
*/
class DefaultController extends Controller
{
	
	private function getTvDbId( $name ) {
		$responseUrl = 'http://thetvdb.com/api/GetSeries.php?seriesname=%s&language=%l';
		$language = "en";
		try {
			$xml = simplexml_load_file( sprintf( $responseUrl, urlencode( $name ), $language ) );
		} catch( ErrorException $e ) {
			return -1;
		}
		
		return $xml->Series[0] != null ? $xml->Series[0]->seriesid : -1;
	}
	
	private function getTvDbSeries( $id ) {
		$api_key = 'C39165096A3B58D7';
		$responseUrl = 'http://thetvdb.com/api/%s/series/%d';
		$xmlFile = sprintf( $responseUrl, $api_key, $id );
		try {
			$xml = simplexml_load_file( $xmlFile );
		} catch( ErrorException $e ) {
			return array();
		}
		
		return $xml->Series[0] != null ? $xml->Series[0] : array();
	}
	
	/**
	* @Route("/")
	* @Template()
	*/
	public function indexAction()
	{
		 
		return $this->render('ShowStopAdminBundle:Default:index.html.twig', array( ) );
	}
	
    /**
     * @Route("/updates/range/{begin}/{end}")
     * @Template()
     */
    public function updateAction($begin,$end)
    {    	
    	//get doctrine entity manager
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$query = $em->createQuery( 'SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.id >= ' .$begin. ' AND s.id < ' .$end );
    	
    	$series = $query->getResult();
    	
    	if (!$series) {
    		throw $this->createNotFoundException( "No television show found");
    	}
    	
    	foreach( $series as $show ) {
    		try{
		    	if( $show->getTvDbId() == null )
		    		$id = $this->getTvDbId( $show->getName() );
		    	else
		    		$id = $show->getTvDbId();
		    	
		    	if( $id >= 0 ) {
			    	//lookup show info by tvdb_id
			    	$xmlShow = $this->getTvDbSeries( $id );
			    	
			    	$show->setDescription( (string)$xmlShow->Overview );
			    	$show->setFirstAired( (string)$xmlShow->FirstAired );
			    	$show->setStatus( (string)$xmlShow->Status );
			    	$show->setNetwork( (string)$xmlShow->Network );
			    	$show->setTvdbId( (int)$xmlShow->id );
	    		}
    		} catch(Exception $e) {
    			
    		}
    	}
    	$em->flush(); 
    	
    	return $this->render('ShowStopAdminBundle:Default:update_complete.html.twig', array('updatedSeries' => $series, 'createdSeries' => array()) );
    }
    
    /**
    * @Route("/updates/new_and_returning")
    * @Template()
    */
    public function returnDatesAction(Request $request)
    {
    	$formats = array();
    	$formats["j/m/Y"] = "j/m/Y";
    	$formats["m/j/Y"] = "m/j/Y";
    	$formats["Y/m/j"] = "Y/m/j";
    	$formats["j-m-Y"] = "j-m-Y";
    	$formats["m-j-Y"] = "m-j-Y";
    	$formats["Y-m-j"] = "Y-m-j";
    	
    	$form = $this->createFormBuilder( array() )
    		->add('records', 'textarea')
    		->add('formats', 'choice', array(
    			'choices' => $formats ) )
    		->getForm();
    	
    	if( $request->getMethod() == "POST" ) {
    		$form->bindRequest($request);
    		
    		$data = $form->getData();
    		$records = explode( "\n", $data["records"] );
    		
    		$format = trim( $data["formats"] );
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$repository = $em->getRepository('ShowStopTelevisionBundle:Series');
    		
    		
    		$createdSeries = array();
    		$updatedSeries = array();
    		
    		foreach( $records as $record ) {
    			$fields = explode( "|", $record );
    			$showName 	= trim( $fields[0] );
    			$returnDate = trim( $fields[1] );
    			$network 	= trim( $fields[2] );
    			
    			
    			$series = $repository->findOneByName( $showName );
    			
    			$returnDate = date_create_from_format( $format, $returnDate );
				
    			//if exists, update
     			if( $series ) { 
    				$series->setNetwork( $network );
    				if( !$returnDate )
						throw $this->createNotFoundException( "Show= " . $fields[0] . ", Date= ". $fields[1] . ", Network= " . $fields[2] . "Format= " . $format );
    				$series->setReturnDate( $returnDate->format('Y-m-d') );
    				$updatedSeries[] = $series;
    			} 
    			//else create new entry
    			else { 
    				$series = new Series();
    				$series->setName( $showName );
    				$series->setNetwork( $network );
    				if( !$returnDate )
    					throw $this->createNotFoundException( "Show= " . $fields[0] . ", Date= ". $fields[1] . ", Network= " . $fields[2] . "Format= " . $format );
    				$series->setReturnDate( $returnDate->format('Y-m-d') );
    				
    				//lookup other details on the tvdb
    				$id = $this->getTvDbId( $showName );
    				if( $id >= 0 ) {
    					$xmlShow = $this->getTvDbSeries( $id );
    					$series->setDescription( (string)$xmlShow->Overview );
    					$series->setFirstAired( (string)$xmlShow->FirstAired );
    					$series->setStatus( (string)$xmlShow->Status );
    					$series->setNetwork( (string)$xmlShow->Network );
    					$series->setTvdbId( (int)$xmlShow->id );
    				}
    				
    				//set object to be managed
    				$em->persist( $series );
    				$createdSeries[] = $series;
    			}
    			
    		}
    		//commit all the changes to the db
    		$em->flush();
    		return $this->render('ShowStopAdminBundle:Default:update_complete.html.twig', array('updatedSeries' => $updatedSeries, 'createdSeries' => $createdSeries ) );

    	}
    	return $this->render('ShowStopAdminBundle:Default:return_dates.html.twig', array('form' => $form->createView() ) );
    	 
    }
    
    /**
    * @Route("/updates/check/{time}")
    * @Template()
    */
    //time=1318079692
    public function updateCheckAction( $time )
    {
    	$updateList = 'http://thetvdb.com/api/Updates.php?time=' . $time;
    	$xml = simplexml_load_file( $updateList );
    	
    	$em = $this->getDoctrine()->getEntityManager();
    	$repository = $em->getRepository('ShowStopTelevisionBundle:Series');
    	
    	$updatedSeries = array();
    	$createdSeries = array();
    	
    	foreach( $xml->Series as $id  ) {

	    		//lookup show on tvdb with $tvID
	    		unset( $xmlShow );
	    		$xmlShow = $this->getTvDbSeries( $id );
	    		
	    		//lookup show with tvdbid from the repository
	    		$series = $repository->findOneByTvDbID( $id );
	    		
	    		//if exists, update
	    		if( !$series ) {
	    			$series = new Series();
	    			$series->setName( (string)$xmlShow->SeriesName );
	    			$series->setTvDbID( (int)$xmlShow->id );
	    			$series->setDescription( (string)$xmlShow->Overview );
	    			$series->setFirstAired( (string)$xmlShow->FirstAired );
	    			$series->setStatus( (string)$xmlShow->Status );
	    			$series->setNetwork( (string)$xmlShow->Network );
	    			
	    			$createdSeries[] = $series;
	    			
	    			//set to be managed
	    			$em->persist( $series );
	    		} else {
	    			$series->setDescription( (string)$xmlShow->Overview );
	    			$series->setFirstAired( (string)$xmlShow->FirstAired );
	    			$series->setStatus( (string)$xmlShow->Status );
	    			$series->setNetwork( (string)$xmlShow->Network );
	    			
	    			$updatedSeries[] = $series;
	    		}
    		
    	}
    	$em->flush();
    	
		return $this->render('ShowStopAdminBundle:Default:update_complete.html.twig', array('updatedSeries' => $updatedSeries, 'createdSeries' => $createdSeries ) );    
    }
}
